import Vue from 'vue' // 导入vue
import VueRouter from 'vue-router' // 导入vue-router

// 导入页面组件
import Index from '@/views/Index'
import About from '@/views/About'
import News from '@/views/News'
import NewsDeatil from '@/views/NewsDeatil'
import Login from '@/views/Login'
import User from '@/views/User'
import UserInfo from '@/views/User/UserInfo'
import UserOrder from '@/views/User/UserOrder'
import UserWelcome from '@/views/User/UserWelcome'
import NotFound from '@/views/NotFound'

// 给vue安装vue-router插件
Vue.use(VueRouter)
// 炉头映射数组
const routes = [
  { path: '/', component: Index, meta: { title: '首页' } },
  { path: '/about', component: About, name: 'about', meta: { title: '公司介绍' } },
  { path: '/news', component: News, meta: { title: '新闻中心' } },
  // 动态路由和命名路由
  { path: '/news/:id', component: NewsDeatil, name: 'newsdetail', meta: { title: '新闻详情' } },
  {
    path: '/user',
    component: User,
    redirect: '/user/index',
    meta: { title: '用户中心', needLogin: true },
    children: [
      { path: 'index', component: UserWelcome, meta: { title: '用户中心-欢迎', needLogin: true } },
      { path: 'info', component: UserInfo, meta: { title: '用户中心-资料', needLogin: true } },
      { path: 'order', component: UserOrder, meta: { title: '用户中心-订单', needLogin: true } }
    ]
  },
  { path: '/login', component: Login, meta: { title: '登录' } },
  // 404 报错页面一定要放在最后去配置
  { path: '/404', component: NotFound, meta: { title: '404' } },
  { path: '*', redirect: '/404' }
]
// 实例化路由对象
const router = new VueRouter({
  routes,
  linkActiveClass: 'active'
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 设置网页标签名
  document.title = to.meta.title
  // 判断要去的界面是否需要登录才可以看到
  if (to.meta.needLogin) {
    // 需要登录
    if (localStorage.getItem('superMagic')) {
      // 登录了
      next()
    } else {
      // 未登录，去登录首页
      next('/login')
    }
  } else {
    // 不需要登录
    next()
  }
})

// 暴露
export default router
